package com.fight.strive.sys.modules.validator;

import com.fight.strive.sys.modules.exception.StriveException;
import com.fight.strive.sys.modules.exception.exceptions.StriveValidException;
import com.fight.strive.sys.utils.ObjectUtils;
import com.fight.strive.sys.utils.ReflectionUtils;
import com.fight.strive.sys.utils.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 验证工具
 */
public class StriveValidateUtils {

    public static void validate(Object obj) {
        try {
            List<Field> fields = ReflectionUtils.getFields(obj);
            for (Field field : fields) {
                field.setAccessible(true);
                Annotation[] annotations = field.getAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation instanceof StriveNotNull) {
                        StriveNotNull striveNotNull = (StriveNotNull) annotation;
                        if (ObjectUtils.isNull(field.get(obj))) {
                            throw new StriveValidException(striveNotNull.msg());
                        }
                    } else if (annotation instanceof StriveNotBlank) {
                        StriveNotBlank striveNotBlank = (StriveNotBlank) annotation;
                        Object val = ReflectionUtils.getFieldValue(obj, field);
                        if (val instanceof String) {
                            if (StringUtils.isEmpty((String) val)) {
                                throw new StriveValidException(striveNotBlank.msg());
                            }
                        } else if (ObjectUtils.isNull(val)) {
                            throw new StriveValidException(striveNotBlank.msg());
                        }
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new StriveException("属性验证访问失败！");
        }
    }
}
